'use strict';

const path = require('path')
const pathExists = require('path-exists')
const fse = require('fs-extra')
const pkgDir = require('pkg-dir')
const npminstall = require('npminstall')

const userHome = require('user-home')

const utils = require('@fs-cli-dev/utils')
const formatPath = require('@fs-cli-dev/format-path')
const { getDefaultRegistry, getNpmLatestVersion } = require('@fs-cli-dev/get-npm-info')


class Package {
    constructor(options) {
        if (!options) {
            throw new Error('Package类的options参数不能为空')
        }
        if (utils.checkType(options) !== 'object') {
            throw new Error('Package类的options参数必须是对象')
        }
        // package路径
        this.targetPath = options.targetPath

        // package存储路径
        this.storeDir = options.storeDir

        this.packageName = options.packageName

        this.packageVersion = options.packageVersion

        // this.getRootFilePath()

        // package的缓存目录前缀
        this.cacheFilePathPrefix = this.packageName.replace('/', "_")

    }

    async prepare() {
        if (this.storeDir && !(await pathExists(this.storeDir))) {
            fse.mkdirp(this.storeDir)
        }
        if (this.packageVersion === 'latest') {
            this.packageVersion = await getNpmLatestVersion(this.packageName)
        }
    }

    get cacheFilePath() {
        return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${this.packageVersion}@${this.packageName}`)
    }
    getSpecficCacheFilePath(packageVersion) {
        return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${packageVersion}@${this.packageName}`)
    }

    // 判断当前package是否存在
    async exists() {
        if (this.storeDir) {
            await this.prepare()
            console.log(this.cacheFilePath);
            return pathExists(this.cacheFilePath)
        } else {
            return pathExists(this.targetPath)
        }
    }

    // 安装package
    async install() {
        await this.prepare()
        return npminstall({
            root: this.targetPath,
            storeDir: this.storeDir,
            registry: getDefaultRegistry(),
            pkgs: [{
                name: this.packageName,
                version: this.packageVersion
            }]
        })
    }

    // 更新package
    async update() {
        await this.prepare()
            // 获取最新npm模块版本号
        const latestPackageVersion = await getNpmLatestVersion(this.packageName)
            // 生成最新
        const latestFilePath = this.getSpecficCacheFilePath(latestPackageVersion)
        if (!(await pathExists(latestFilePath))) {
            await npminstall({
                root: this.targetPath,
                storeDir: this.storeDir,
                registry: getDefaultRegistry(),
                pkgs: [{
                    name: this.packageName,
                    version: latestPackageVersion
                }]
            })
            console.log('update version: ', latestPackageVersion);
        }
        this.packageVersion = latestPackageVersion

        return latestFilePath
    }

    // 获取入口文件路径
    async getRootFilePath() {
        async function _getRootFile(targetPath) {
            // 获取package.json所在目录
            const dir = await pkgDir(targetPath)
            if (dir) {
                const pkgFile = require(path.resolve(dir, 'package.json'))
                if (pkgFile && pkgFile.main) {
                    // 路径兼容
                    return formatPath(path.resolve(dir, pkgFile.main))
                }
            }
        }
        // 缓存情况
        if (this.storeDir) {
            return _getRootFile(this.storeDir)
        } else {
            return _getRootFile(this.targetPath)
        }
        return null
    }

}


module.exports = Package;